﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace cls.u_Models
{
    public partial class ShowEmpstat : System.Web.UI.Page
    {
        static String UserName = "";
        static String UserInOrgCode = "";
        static String UserInOrgId = "";
        static Boolean UserInZB = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            UserName = User.Identity.Name;

            if (UserName.Equals(""))
            {
                Response.Redirect("..\\Default.aspx");
            }
            else
            {
                UserInOrgCode = GetOrgCodeByUserName(UserName);
                UserInOrgId = GetOrgIdByUserName(UserName);
            }

            if (UserInOrgCode.Trim().Equals("ZB"))
            {
                UserInZB = true;
            }
            else
            {
                UserInZB = false;
            }

            if (!Page.IsPostBack)
            {
                //EmpstatDetailDataBind(UserInOrgCode);
                DropdownList_ShowOrgNames();
            }
        }

        protected String GetOrgCodeByUserName(String UserName)
        {
            String OrgCode = "";

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT OrgCode FROM u_cls_Org WHERE Id = (SELECT OrgId FROM u_cls_UserInOrg WHERE UserName = @UserName)", SqlConnection);

            SelectCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 4);
            SelectCommand.Parameters["@UserName"].Value = UserName;

            SqlDataReader OrgCodeReader = SelectCommand.ExecuteReader();

            while (OrgCodeReader.Read())
            {
                //还是分开取得比较好，后面还有单独用到OrgCode的地方......
                //OrgCode = ResReader["OrgCode"].ToString() + "-" + ResReader["OrgName"].ToString();  
                OrgCode = OrgCodeReader["OrgCode"].ToString().Trim();
            }

            //if (OrgCode.Equals("ZB"))
            //{
            //   UserInZB = true;
            //}

            OrgCodeReader.Close();
            SqlConnection.Close();

            return OrgCode;
        }

        protected String GetOrgIdByUserName(String UserName)
        {
            String OrgId = "";

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT [OrgId] FROM [dbo].[u_cls_UserInOrg] WHERE [UserName] = @UserName", SqlConnection);

            SelectCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 4);
            SelectCommand.Parameters["@UserName"].Value = UserName;

            SqlDataReader OrgIdReader = SelectCommand.ExecuteReader();

            while (OrgIdReader.Read())
            {
                OrgId = OrgIdReader["OrgId"].ToString().ToUpper();
            }

            OrgIdReader.Close();
            SelectCommand.Dispose();
            SqlConnection.Close();

            return OrgId;
        }

        protected String GetLastInsDatetime(String OrgCode)
        {
            String LastInsDatetime = "";
            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT TOP(1) LastInsDatetime FROM [dbo].[u_cls_LastInsDatetime] WHERE OrgCode = '" + OrgCode + "' AND ApplicationName = 'Empstat' ORDER BY LastInsDatetime DESC", SqlConnection);
            SqlDataReader LastInsDatetimeReader = SelectCommand.ExecuteReader();

            //酱紫写法系错误嘀，乖乖的用While循环吧......
            //if(LastInsDatetimeReader.HasRows)
            //{
            //    LastInsDatetime = LastInsDatetimeReader["LastInsDatetime"].ToString();
            //}
            while (LastInsDatetimeReader.Read())
            {
                LastInsDatetime = LastInsDatetimeReader["LastInsDatetime"].ToString();
            }

            LastInsDatetimeReader.Close();
            SqlConnection.Close();

            return LastInsDatetime;
        }

        protected DataSet EmpstatDetailDateSet(String OrgCode, String LastInsDatetime)
        {
            DataSet EmpstatDetailDateSet = new DataSet();

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            //String SelectCommandString = "SELECT [id],[OrgCode],[OrgName],[StdCount],[ExiCount],[DepCount],[NcCount],[NtCount],[NdCount],[EmpNames],[LastModifyDatetime] FROM [dbo].[u_cls_Empstat_Table] WHERE [ImportDatetime] = '" + LastInsDatetime + "'";

            //2014-11-18修改，更新模版
            //问题：ImportDatetime不使用参数化，会导致丢失毫秒
            String SelectCommandString = "SELECT [Id],[OrgCode],[OrgName],[StdCount],[EmpNames],[EmpSex],[EmpTitle],[EmpJoinDate],[EmpAddr],[EmpMobile],[ImportDatetime],[ImportUserName],[LastModifyDatetime],[LastModifyUserName],[StatDatetime] FROM [dbo].[u_cls_Empstat_Table]";

            //是否选择了OrgCode
            if (OrgCode.Equals("all"))
            {
                //总部查看，大于或等于本月第一天Import的信息。
                //问题：ImportDatetime不使用参数化，会导致丢失毫秒，故此处使用CONVERT
                //SelectCommandString += " WHERE [ImportDatetime] >= DATEADD(MONTH, DATEDIFF(MONTH,0,getdate()), 0)";
                SelectCommandString += " WHERE [ImportDatetime] IN (SELECT CONVERT(nvarchar, LastInsDatetime,120) FROM [dbo].[u_cls_LastInsDatetime] WHERE ApplicationName = 'Empstat')";
            }
            else
            {
                //门店查看，分别取得不同门店的最后Import时间
                SelectCommandString += " WHERE [ImportDatetime] = '" + LastInsDatetime + "'" + " AND OrgCode='" + OrgCode + "'";
            }

            SelectCommandString += " ORDER BY [OrgCode]";

            SqlDataAdapter dataAdapter = new SqlDataAdapter(SelectCommandString, SqlConnection);
            dataAdapter.Fill(EmpstatDetailDateSet);

            dataAdapter.Dispose();
            SqlConnection.Close();

            return EmpstatDetailDateSet;
        }

        protected void EmpstatDetailDataBind(String OrgCode, Boolean ShowFooter)
        {
            GridView_Empstat.AutoGenerateColumns = false;
            GridView_Empstat.Columns.Clear();

            GridView_Empstat.DataSource = EmpstatDetailDateSet(OrgCode, GetLastInsDatetime(OrgCode));
            GridView_Empstat.DataKeyNames = new string[] { "id" };

            BoundField bField;

            bField = new BoundField();
            bField.DataField = "id";
            bField.HeaderText = "编号";
            bField.ReadOnly = true;
            bField.Visible = false;
            GridView_Empstat.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "OrgCode";
            bField.HeaderText = "组织编码";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Empstat.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "OrgName";
            bField.HeaderText = "组织名称";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Empstat.Columns.Add(bField);

            //[3]
            bField = new BoundField();
            bField.DataField = "StdCount";
            bField.HeaderText = "编制人数";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Empstat.Columns.Add(bField);

            //[4]
            //bField = new BoundField();
            //bField.DataField = "ExiCount";
            //bField.HeaderText = "现有人数";
            //bField.ReadOnly = UserInZB;
            //bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            //bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //GridView_Empstat.Columns.Add(bField);

            //[5]
            //bField = new BoundField();
            //bField.DataField = "DepCount";
            //bField.HeaderText = "离职人数";
            //bField.ReadOnly = UserInZB;
            ////bField.DataFormatString = "{0:D}";
            //bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            //bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //GridView_Empstat.Columns.Add(bField);

            //[6]
            //bField = new BoundField();
            //bField.DataField = "NcCount";
            //bField.HeaderText = "收银员需求数量";
            //bField.ReadOnly = UserInZB;
            //bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            //bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //GridView_Empstat.Columns.Add(bField);

            //[7]
            //bField = new BoundField();
            //bField.DataField = "NtCount";
            //bField.HeaderText = "理货员需求数量";
            //bField.ReadOnly = UserInZB;
            //bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            //bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //GridView_Empstat.Columns.Add(bField);

            //[8]
            //bField = new BoundField();
            //bField.DataField = "NdCount";
            //bField.HeaderText = "送货员需求数量";
            //bField.ReadOnly = UserInZB;
            //bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            //bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            //GridView_Empstat.Columns.Add(bField);

            //[4]
            bField = new BoundField();
            bField.DataField = "EmpNames";
            bField.HeaderText = "员工姓名";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Empstat.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "EmpSex";
            bField.HeaderText = "员工性别";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Empstat.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "EmpTitle";
            bField.HeaderText = "员工职位";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Empstat.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "EmpJoinDate";
            bField.HeaderText = "入职时间";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Empstat.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "EmpAddr";
            bField.HeaderText = "现在住址";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Empstat.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "EmpMobile";
            bField.HeaderText = "联系电话";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Empstat.Columns.Add(bField);

            if (UserInZB)
            {
                bField = new BoundField();
                bField.DataField = "ImportDatetime";
                bField.HeaderText = "上传时间";
                bField.ReadOnly = true;
                GridView_Empstat.Columns.Add(bField);

                bField = new BoundField();
                bField.DataField = "ImportUserName";
                bField.HeaderText = "上传用户";
                bField.ReadOnly = true;
                GridView_Empstat.Columns.Add(bField);

                bField = new BoundField();
                bField.DataField = "LastModifyDatetime";
                bField.HeaderText = "最后修改时间";
                bField.ReadOnly = true;
                GridView_Empstat.Columns.Add(bField);
            }
            else
            {
                CommandField cfEdit = new CommandField();
                cfEdit.ButtonType = ButtonType.Link;
                cfEdit.EditText = "编辑";
                cfEdit.ShowEditButton = true;
                cfEdit.UpdateText = "更新";
                cfEdit.CancelText = "取消";
                cfEdit.ItemStyle.Wrap = false;
                GridView_Empstat.Columns.Add(cfEdit);
            }

            GridView_Empstat.HeaderStyle.Font.Size = 8;
            GridView_Empstat.DataBind();

            //显示页脚合计
            GridView_Empstat_CosFooter(ShowFooter);
        }

        protected void GridView_Empstat_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //Set the edit index.
            GridView_Empstat.EditIndex = e.NewEditIndex;
            //GridView_Empstat.EditRowStyle.Width = 40;

            //Bind data to the GridView control. 
            //必须
            EmpstatDetailDataBind(UserInOrgCode, false);
        }

        protected void GridView_Empstat_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //不是必须赋值
            //如用户删除TextBox内文本，会造成ClsCode = ""。
            //OrgCode = DropDownList_SelectOrgCode.SelectedValue;
            //ClsCode = TextBox_InputClsCode.Text;
            //PluCode = TextBox_InputPluCode.Text;

            //Reset the edit index.
            GridView_Empstat.EditIndex = -1;

            //Bind data to the GridView control.
            EmpstatDetailDataBind(UserInOrgCode, true);
        }

        protected void GridView_Empstat_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            String id = GridView_Empstat.DataKeys[e.RowIndex]["id"].ToString();

            //取值
            //2014-11-19修改，更新表结构
            //String ExiCount = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[4].Controls[0]).Text;           
            //String DepCount = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
            //String NcCount = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[6].Controls[0]).Text;
            //String NtCount = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[7].Controls[0]).Text;
            //String NdCount = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[8].Controls[0]).Text;
            //String EmpNames = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[9].Controls[0]).Text;

            //员工姓名
            String EmpNames = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
            //员工性别
            String EmpSex = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
            //员工职位
            String EmpTitle = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[6].Controls[0]).Text;
            //入职时间
            String EmpJoinDate = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[7].Controls[0]).Text;
            //现在住址
            String EmpAddr = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[8].Controls[0]).Text;
            //联系电话
            String EmpMobile = ((TextBox)GridView_Empstat.Rows[e.RowIndex].Cells[9].Controls[0]).Text;

            //2014-11-19修改，更新表结构
            //GridView_Empstat_RowUpdate(false, id, ExiCount, DepCount, NcCount, NtCount, NdCount, EmpNames);

            GridView_Empstat_RowUpdate(false, id, EmpNames, EmpSex, EmpTitle, EmpJoinDate, EmpAddr, EmpMobile);

            //Reset the edit index.
            GridView_Empstat.EditIndex = -1;

            EmpstatDetailDataBind(UserInOrgCode, true);
        }

        protected void GridView_Empstat_RowUpdate(Boolean UserInZB, String id, String EmpNames, String EmpSex, String EmpTitle, String EmpJoinDate, String EmpAddr, String EmpMobile)
        {
            DateTime LastModifyDatetime = DateTime.Now;

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand UpdateCommand = new SqlCommand();

            String UpdateString = "";
            if (UserInZB)
            {
                //UpdateString = "UPDATE [dbo].[u_cls_Empstat_Table] SET [ClsResp] = @ClsResp WHERE [Id] = @Id";
                //UpdateCommand.CommandText = UpdateString;
                //UpdateCommand.CommandType = CommandType.Text;
                //UpdateCommand.Connection = SqlConnection;

                //UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
                //UpdateCommand.Parameters.Add("@ClsResp", SqlDbType.NVarChar, 4000);

                ////必须转换
                ////Exception Details: System.InvalidCastException: Invalid cast from 'System.String' to 'System.Guid'.
                //UpdateCommand.Parameters["@id"].Value = new System.Guid(id);
                //UpdateCommand.Parameters["@ClsResp"].Value = EmpNames;

                //UpdateCommand.ExecuteNonQuery();
            }
            else
            {
                //2014-11-19修改，更新表结构
                //UpdateString = "UPDATE [dbo].[u_cls_Empstat_Table] SET [ExiCount] = @ExiCount,[DepCount] = @DepCount,[NcCount] = @NcCount,[NtCount] = @NtCount,[NdCount] = @NdCount, [EmpNames] = @EmpNames, [LastModifyDatetime] = @LastModifyDatetime WHERE [Id]=@Id";

                UpdateString = "UPDATE [dbo].[u_cls_Empstat_Table] SET [EmpNames] = @EmpNames,[EmpSex] = @EmpSex,[EmpTitle] = @EmpTitle,[EmpJoinDate] = @EmpJoinDate,[EmpAddr] = @EmpAddr, [EmpMobile] = @EmpMobile, [LastModifyDatetime] = @LastModifyDatetime WHERE [Id]=@Id";

                UpdateCommand.CommandText = UpdateString;
                UpdateCommand.CommandType = CommandType.Text;
                UpdateCommand.Connection = SqlConnection;

                UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
                UpdateCommand.Parameters.Add("@EmpNames", SqlDbType.NVarChar, 4);
                UpdateCommand.Parameters.Add("@EmpSex", SqlDbType.NVarChar, 2);
                UpdateCommand.Parameters.Add("@EmpTitle", SqlDbType.NVarChar, 10);
                UpdateCommand.Parameters.Add("@EmpJoinDate", SqlDbType.NVarChar, 50);
                UpdateCommand.Parameters.Add("@EmpAddr", SqlDbType.NVarChar, 4000);
                UpdateCommand.Parameters.Add("@EmpMobile", SqlDbType.NChar, 11);
                UpdateCommand.Parameters.Add("@LastModifyDatetime", SqlDbType.DateTime);

                UpdateCommand.Parameters["@id"].Value = new System.Guid(id);

                //2014-11-19修改，更新表结构
                //UpdateCommand.Parameters["@ExiCount"].Value = Int32.Parse(ExiCount);
                //UpdateCommand.Parameters["@DepCount"].Value = Int32.Parse(DepCount);
                //UpdateCommand.Parameters["@NcCount"].Value = Int32.Parse(NcCount);
                //UpdateCommand.Parameters["@NtCount"].Value = Int32.Parse(NtCount);
                //UpdateCommand.Parameters["@NdCount"].Value = Int32.Parse(NdCount);

                UpdateCommand.Parameters["@EmpNames"].Value = EmpNames;
                UpdateCommand.Parameters["@EmpSex"].Value = EmpSex;
                UpdateCommand.Parameters["@EmpTitle"].Value = EmpTitle;
                UpdateCommand.Parameters["@EmpJoinDate"].Value = EmpJoinDate;
                UpdateCommand.Parameters["@EmpAddr"].Value = EmpAddr;
                UpdateCommand.Parameters["@EmpMobile"].Value = EmpMobile;
                UpdateCommand.Parameters["@LastModifyDatetime"].Value = LastModifyDatetime;
            }

            try
            {
                UpdateCommand.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                //Label_ErrorMsg.Text = se.Message;
                //Label_ErrorMsg.Visible = true;
            }

            UpdateCommand.Dispose();
            SqlConnection.Close();
        }

        protected void DropdownList_ShowOrgNames()
        {
            DropDownList_SelectOrgCode.Items.Clear();

            String SelectCommandString = "";

            if (UserInOrgCode.Trim().Equals("ZB"))
            {
                DropDownList_SelectOrgCode.Items.Add(new ListItem("全部", "all"));
                SelectCommandString = "SELECT OrgCode,OrgName FROM [dbo].[u_cls_Org] ORDER BY OrgCode";
            }
            else
            {
                SelectCommandString = "SELECT OrgCode,OrgName FROM [dbo].[u_cls_Org] WHERE Id = '" + UserInOrgId + "' ORDER BY OrgCode";
            }

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand(SelectCommandString, SqlConnection);
            SqlDataReader OrgCodeReader = SelectCommand.ExecuteReader();

            while (OrgCodeReader.Read())
            {
                DropDownList_SelectOrgCode.Items.Add(new ListItem(OrgCodeReader["OrgCode"].ToString() + "-" + OrgCodeReader["OrgName"].ToString(), OrgCodeReader["OrgCode"].ToString()));
            }

            OrgCodeReader.Close();
            SelectCommand.Dispose();
            SqlConnection.Close();
        }

        protected void Button_ShowEmpStatDetail_Click(object sender, EventArgs e)
        {
            GridView_Empstat.EmptyDataText = "您的查询条件没有结果。";

            UserInOrgCode = DropDownList_SelectOrgCode.SelectedValue;

            EmpstatDetailDataBind(UserInOrgCode, true);
        }

        protected void Button_Return_Click(object sender, EventArgs e)
        {
            Response.Redirect("EmpstatMgr.aspx");
        }

        protected void GridView_Empstat_CosFooter(Boolean ShowFooter)
        {
            if (ShowFooter)
            {
                if (GridView_Empstat.Rows.Count > 0)
                {
                    Decimal _StdCount = 0m;

                    //取消合计
                    //Decimal _ExiCount = 0m;
                    //Decimal _DepCount = 0m;
                    //Decimal _NcCount = 0m;
                    //Decimal _NtCount = 0m;
                    //Decimal _NdCount = 0m;

                    for (int i = 0; i < GridView_Empstat.Rows.Count; i++)
                    {
                        if (GridView_Empstat.Rows[i].RowType == DataControlRowType.DataRow)
                        {
                            //_StdCount += Convert.ToDecimal(GridView_Empstat.Rows[i].Cells[3].Text);

                            //更改列合计为行数合计
                            _StdCount = Convert.ToDecimal(i + 1);

                            //取消以下列合计
                            //_ExiCount += Convert.ToDecimal(GridView_Empstat.Rows[i].Cells[4].Text);
                            //_DepCount += Convert.ToDecimal(GridView_Empstat.Rows[i].Cells[5].Text);
                            //_NcCount += Convert.ToDecimal(GridView_Empstat.Rows[i].Cells[6].Text);
                            //_NtCount += Convert.ToDecimal(GridView_Empstat.Rows[i].Cells[7].Text);
                            //_NdCount += Convert.ToDecimal(GridView_Empstat.Rows[i].Cells[8].Text);
                        }
                    }

                    GridView_Empstat.FooterRow.Cells[1].Wrap = false;
                    GridView_Empstat.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Center;
                    GridView_Empstat.FooterRow.Cells[1].Text = "合计员工数：";
                    GridView_Empstat.FooterRow.Cells[3].HorizontalAlign = HorizontalAlign.Center;
                    GridView_Empstat.FooterRow.Cells[3].Text = _StdCount.ToString();

                    //取消显示合计信息
                    //GridView_Empstat.FooterRow.Cells[4].HorizontalAlign = HorizontalAlign.Center;
                    //GridView_Empstat.FooterRow.Cells[4].Text = _ExiCount.ToString();
                    //GridView_Empstat.FooterRow.Cells[5].HorizontalAlign = HorizontalAlign.Center;
                    //GridView_Empstat.FooterRow.Cells[5].Text = _DepCount.ToString();
                    //GridView_Empstat.FooterRow.Cells[6].HorizontalAlign = HorizontalAlign.Center;
                    //GridView_Empstat.FooterRow.Cells[6].Text = _NcCount.ToString();
                    //GridView_Empstat.FooterRow.Cells[7].HorizontalAlign = HorizontalAlign.Center;
                    //GridView_Empstat.FooterRow.Cells[7].Text = _NtCount.ToString();
                    //GridView_Empstat.FooterRow.Cells[8].HorizontalAlign = HorizontalAlign.Center;
                    //GridView_Empstat.FooterRow.Cells[8].Text = _NdCount.ToString();
                }
            }
        }

        protected void Button_Export_Click(object sender, EventArgs e)
        {
            //文件名只能是.xls，.xlsx会导致文件无法打开（Office 2013 X64）
            ExportToExcel(null, GridView_Empstat, UserInOrgCode + "_" + UserName + "_" + DateTime.Now + "_导出.xls");
        }

        //参考资料
        //http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
        //http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp22_dc04022007235740PM/exportxl_asp22_dc.aspx?ArticleID=1195fe8c-c6f5-4d52-925b-953f4b9de344
        private void ExportToExcel(string FileType, GridView SourceGV, string FileName)
        {
            //参考资料
            //http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
            //http://www.cnblogs.com/sparon/archive/2007/04/06/702946.html
            //
            //Office 2007 File Format MIME Types for HTTP Content Streaming
            //http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/05/08/office-2007-open-xml-mime-types.aspx

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", FileName));

            //HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a table to contain the grid
                    Table table = new Table();

                    //  include the gridline settings
                    table.GridLines = SourceGV.GridLines;

                    //  add the header row to the table
                    if (SourceGV.HeaderRow != null)
                    {
                        ShowEmpstat.PrepareControlForExport(SourceGV.HeaderRow);
                        table.Rows.Add(SourceGV.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in SourceGV.Rows)
                    {
                        ShowEmpstat.PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (SourceGV.FooterRow != null)
                    {
                        ShowEmpstat.PrepareControlForExport(SourceGV.FooterRow);
                        table.Rows.Add(SourceGV.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }

        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    ShowEmpstat.PrepareControlForExport(current);
                }
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        { }
    }
}